/*
 * @Descripttion: 
 * @Author: junhuafly
 * @Date: 2020-02-27 12:04:47
 * @LastEditors: junhuafly
 * @Email: junhuafly@163.com
 * @LastEditTime: 2020-04-15 18:59:28
 */
// pages/goods/detail.js
const app = getApp()
import {
  utils
} from './../../../components/lib/utils'
import {
  goodsAPI,
  orderAPI
} from "./../../../api/index.js"

import {
  returnStatus,
  handleCollect,
  getPromise,
} from '../../../utils/util'

Page({
  onShareAppMessage() {
    return {
      title: 'swiper',
      path: 'page/component/pages/swiper/swiper'
    }
  },

  data: {
    show: false,
    showNav: true,
    showPopup: false,
    showShearProp: false,
    showChoose: false,
    showCoupon: false,
    productId: 63,
    goodsInfo:{},
    goodsImages:[],
    goodsImagesDetail:[],
    coupons:[],
    buyers:[],
    screenWidth: 375,
    rates:[],
    isSKU: false,
    active:'item0'
  },

  changeIndicatorDots() {
    this.setData({
      indicatorDots: !this.data.indicatorDots
    })
  },
  closeCoupon() {
      this.setData({showCoupon:false})
  },

  // 获取优惠列表信息
  async openCoupon() {
    // 获取该商品优惠信息
    const res = await goodsAPI.queryGoodsByCoupons({productId:this.data.productId})
    const _ = await returnStatus(res)
    if(_){
      this.setData({
        coupons:_
      })
    }
    this.setData({showCoupon:true})
  },
  jumpTo ({detail:{name}}) {
    // 获取标签元素上自定义的 data-opt 属性的值
    this.setData({
        toView: name
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function ({id:productId}) {
    var appInst =  getApp();
    
    const isIphoneX = appInst.globalData.isIphoneX
    this.setData({
      isIphoneX,
      productId:productId*1
    })
    this.pageNum = 1
    let {screenWidth} = wx.getSystemInfoSync();
     const params = {
      productId:this.data.productId
    }
    // 获取商品基础信息
    const info = ['queryGoodsBaseInfo','queryGoodsImages','queryGoodsImagesDetail']
    const info_key = ['goodsInfo','goodsImages','goodsImagesDetail']
    this.getPromise(info,info_key).then(()=>{
      // 解析尺码
      let sizeDataTemp=null
      let sizeData = []
      try {
        sizeDataTemp = JSON.parse(this.data.goodsInfo.sizeInfo) || []
        sizeDataTemp.map(item => {
          item = item.split(',')
          sizeData.push(item)
        })
        this.setData({
          sizeData,
          disableSku: this.data.goodsInfo.productStatus===1,
          screenWidth
        })
      } catch (error) {
        console.error('解析商品尺寸信息出错', error)
      }
    })
    
    // 获取其他信息
    this.getOtherInfo()
    
    // 获取滚动信息
    goodsAPI.queryGoodsCanBuy(params).then(async res=>{
      const canBuy = await returnStatus(res)
      this.setData({
        canBuy
      })
    })
    // 评论
    this.getGoodsRate()
  },
  // 通过promise合并请求获取数据
  getPromise(info,info_key,type='all'){
    const params = {
      productId:this.data.productId
    }
    return getPromise.call(this,info,info_key,{params,API:goodsAPI})
    // let promise =[]
    // info.forEach(item=>{
    //   promise.push(
    //     new Promise((resolve, reject) => {
    //      goodsAPI[item](params).then(async res=>{
    //       const _ = await returnStatus(res)
    //       _?resolve(_):reject(false)
    //     })
    //   }))
    // })
    // return Promise[type](promise).then(res=>{
    //   res.forEach((item,index)=>{
    //     const key = info_key[index]
    //     this.setData({
    //       [key]:item
    //     })
    //   })
    // })
  },
  // 获取商品评论
  async getGoodsRate(){
    this.setData({
      loading:true
    })
    const res = await goodsAPI.queryGoodsRate({
      pageNum:this.pageNum,
      pageSize:5,
      productId:this.data.productId
    })
    const {records,pages} = await returnStatus(res)
    records.map(item=>{
      item.createDate = utils.relativeTime(item.createDate)
    })
    this.setData({
      rates:[...this.data.rates,...records],
      loading:false,
      finish:pages===0||this.pageNum===pages
    })
    this.pageNum++
  },
  // 获取其他信息
  async getOtherInfo(){
    const info = ['queryGoodsDiscounts','queryGoodsByBuyer','queryGoodsCollection']
    const info_key = ['discounts','buyers','isCollect']
    if(!wx.getStorageSync('token')) {
      info.pop()
      info_key.pop()
    }
    await this.getPromise(info,info_key)
  },
  // 查询该商品销售信息
  // async getGoodsSaleInfo(){
  //   getSkuInfo.call(this)
  // },
// 显示销售信息
  showSKU({target:{dataset:{type}}}){
    this.type = type
    // this.getGoodsSaleInfo()
    this.setData({'goodsInfo.productId':this.data.productId,isSKU:true})
  },
// 得到销售sku 信息
  async getSku({detail:{storageId,quantity}}){
    // 添加到购物车
    if(this.type === 'cart'){
      const res = await orderAPI.handleCart({
        method:'post',
        quantity,
        storageId
      })
      const _ = await returnStatus(res)
      if(_){
         wx.showToast({
           title: _,
           icon: 'none',
         });
      }
      // 直接购买
    }else{
      const res = await  orderAPI.handleBuyGoods({
          "orderFrom": 3,
          quantity,
          storageId
        })
      const _ = await returnStatus(res)
      if(_){
        console.log(_); // 2911 订单id
        // 去付款
        wx.navigateTo({
          url: '/pages/queryOrder/index?orderId='+_,
        })
        
      }
    }
    this.setData({isSKU:false})
    
  },
  // 关闭sku
  closeSKU(){
    this.setData({'goodsInfo.productId':0,isSKU:false})
  },
  // 操作收藏
  handleCollect(){
    handleCollect.call(this,this.data.productId,this.data.isCollect,'isCollect')
  },

  // 禁止滑动
  forbidMove(){
    return false
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})